<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2019-2020 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: MUKE <513038996@qq.com>
// +----------------------------------------------------------------------
namespace app\admin\controller;

use think\facade\Db;
use think\facade\View;
use think\exception\ValidateException;
use app\admin\BaseController;
use app\addons\File;
use app\admin\model\AdminMenu as MenuModel;
use app\admin\validate\AdminMenu as MenuValidate;
/**
 * 管理员菜单管理
 */
class AdminMenu extends BaseController
{
    /**
     * 显示资源列表
     */
    public function index()
    {
        if ($this->request->isPost()) {
            return json([
                'status'     => 'success', 
                'message'    => '请求成功', 
                'data'       => $this->request->menu, 
                'publicMenu' => $this->request->publicMenu,
            ]);
        } else {
            return View::fetch();
        }
    }

    /**
     * 保存更新的资源
     */
    public function update()
    {
        try {
            $input = input();
            if (! is_string($input['id'])) {
                validate(MenuValidate::class)->check($input);
                $exist = MenuModel::where('path', $input['path'])->where('id', '<>', $input['id'])->find();
                if (! $exist) {
                    $save  = MenuModel::find($input['id']);
                    $save->pid        = $input['pid'];
                    $save->title      = $input['title'];
                    $save->icon       = $input['icon'];
                    $save->path       = $input['path'];
                    $save->sort       = $input['sort'];
                    $save->status     = $input['status'];
                    $save->ifshow     = $input['ifshow'];
                    $save->logwriting = $input['logwriting'];
                    $save->save();
                } else {
                    return json(['status' => 'error', 'message' => '路径不能重复']);
                }
            } else {
                $path = explode('/', $input['path']);
                $name = $path[0];
                unset($path[0]);
                $path = implode('/', $path);
                $file = plugin_path() . $name . '/menu.php';
                $menu = include($file);
                foreach ($menu as $key1 => $val1) {
                    if ($path === $val1['path']) {
                        $menu[$key1]['title'] = $input['title'];
                        $menu[$key1]['status'] = $input['status'];
                        $menu[$key1]['ifshow'] = $input['ifshow'];
                        $menu[$key1]['logwriting'] = $input['logwriting'];
                    }
                    if (isset($menu[$key1]['children'])) {
                        foreach ($menu[$key1]['children'] as $key2 => $val2) {
                            if ($path === $val2['path']) {
                                $menu[$key1]['children'][$key2]['title'] = $input['title'];
                                $menu[$key1]['children'][$key2]['status'] = $input['status'];
                                $menu[$key1]['children'][$key2]['ifshow'] = $input['ifshow'];
                                $menu[$key1]['children'][$key2]['logwriting'] = $input['logwriting'];
                            }
                            if (isset($menu[$key1]['children'][$key2]['children'])) {
                                foreach ($menu[$key1]['children'][$key2]['children'] as $key3 => $val3) {
                                    if ($path === $val3['path']) {
                                        $menu[$key1]['children'][$key2]['children'][$key3]['title'] = $input['title'];
                                        $menu[$key1]['children'][$key2]['children'][$key3]['status'] = $input['status'];
                                        $menu[$key1]['children'][$key2]['children'][$key3]['ifshow'] = $input['ifshow'];
                                        $menu[$key1]['children'][$key2]['children'][$key3]['logwriting'] = $input['logwriting'];
                                    }
                                }
                            }
                        }
                    }
                }
                // 写入文件
                $content = "<?php\nreturn ".var_export($menu,true).";";
                File::create($file, $content);
            }
            return json(['status' => 'success', 'message' => '修改成功']);
        } catch ( ValidateException $e ) {
            return json($e->getError());
        }
    }

    /**
     * 删除指定资源
     */
    public function delete()
    {
        try {
            $input = input();
            validate(MenuValidate::class)->scene('delete')->check($input);
            MenuModel::recursiveDestroy($input['ids']);
            return json(['status' => 'success', 'message' => '删除成功']);
        } catch ( ValidateException $e ) {
            return json($e->getError());
        }
    }
    
    /**
     * 保存新建的资源
     */
    public function save()
    {
        try {
            $input = input();
            validate(MenuValidate::class)->scene('save')->check($input);
            $path  = $input['curd'] == 1 ? strtolower(str_replace('mk_','', $input['path'])).'/index' : $input['path'];
            $exist = MenuModel::where('path', $path)->find();
            if (! $exist) {
                $parent = MenuModel::create([
                    'pid'        => $input['pid'],
                    'title'      => $input['title'],
                    'icon'       => $input['icon'],
                    'path'       => $path,
                    'sort'       => $input['sort'],
                    'status'     => $input['status'],
                    'ifshow'     => $input['ifshow'],
                    'logwriting' => $input['logwriting'],
                ]);
                if ($input['curd'] == 1) {
                    $exist = Db::query("SHOW TABLES LIKE '".$input['path']."'");
                    if (! empty($exist)) {
                        $field = Db::query("SHOW COLUMNS FROM ".$input['path']."");
                        $path  = strtolower(str_replace('mk_','', $input['path']));
                        $class = ucfirst($path);
                        $curd  = include(app_path() . "addons/Curd.php");
                        File::create(app_path() . "controller/$class.php", $controller);
                        File::create(app_path() . "model/$class.php", $model);
                        File::create(app_path() . "view/$path/index.html", $view);
                        $curd = [
                            ['title' => '编辑', 'path' => $path . '/update'],
                            ['title' => '删除', 'path' => $path . '/delete'],
                            ['title' => '新增', 'path' => $path . '/save'],
                            ['title' => '查看', 'path' => $path . '/index'],
                        ];
                        foreach ($curd as $key => $val) {
                            MenuModel::create([
                                'pid'        => $parent->id,
                                'title'      => $val['title'],
                                'icon'       => '',
                                'path'       => $val['path'],
                                'sort'       => $key,
                                'status'     => $input['status'],
                                'ifshow'     => 0,
                                'logwriting' => $input['logwriting'],
                            ]);
                        }
                    } else {
                        return json(['status' => 'error', 'message' => '表名不存在！']);
                    }
                }
                return json(['status' => 'success', 'message' => '新增成功']);
            } else {
                return json(['status' => 'error', 'message' => '路径不能重复']);
            }
        } catch ( ValidateException $e ) {
            return json($e->getError());
        }
    }
}
